angular.module('U9ImHd.utility')

.factory('Connect', ['$q', '$http', 'Config', 'APPCONSTANTS',
    function($q, $http, Config, APPCONSTANTS) {
        var connectDefer = $q.defer(),
            o = {
                loaded: connectDefer.promise
            };

        var _connect = {},
            _serveParameter = {};

        o.set = function (address, port, serveParameter) {
            var defer = $q.defer();

            _connect.address = address;
            _connect.port = port;
            _serveParameter = serveParameter;

            Config.set(_connect).finally(function () {
                defer.resolve();
            });

            return defer.promise;
        };
        o.get = function (key) {
            return key ? _connect[key] : angular.copy(_connect);
        };
        o.getServeParameter = function (key) {
            return key ? _serveParameter[key] : angular.copy(_serveParameter);
        };
        o.test = function (address, port) {
            var defer = $q.defer();

            $http({
                method: 'POST',
                url: 'http://' + address + ':' + port + APPCONSTANTS.connectTestURL,
                timeout: APPCONSTANTS.httpTimeOut
            }).then(function (result) {
                if (!result.data) {
                    defer.reject();
                } else if (result.data.Data) {
                    defer.resolve(result.data.Data);
                } else {
                    defer.reject(result.data.Error);
                }
            }, function (err) {
                defer.reject(err);
            });

            return defer.promise;
        };

        init();

        return o;

        function init () {
            Config.loaded.finally(function () {
                var address = Config.get('address'),
                    port = Config.get('port');

                if (address && port) {
                    o.test(address, port).then(function (data) {
                        if (data && data.GatewayAddress) {
                            _connect.address = address;
                            _connect.port = port;
                            _serveParameter = data;
                        }
                    }).finally(function () {
                        connectDefer.resolve();
                    });
                } else {
                    connectDefer.resolve();
                }
            });
        }
    }
]);
